<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for='shopList in shopCartList' :key='shopList.id'>
          <li class="cart-list-con1">
            <input type="checkbox" name="chk_list" :checked='!!shopList.isChecked' @change='checkedCartInfo(shopList)'>
          </li>
          <li class="cart-list-con2">
            <img :src="shopList.imgUrl">
            <div class="item-msg">{{shopList.skuName}}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{shopList.skuPrice}}.00</span>
          </li>
          <li class="cart-list-con5">
            <a href="javascript:void(0)" class="mins" @click='changeSkuNum("decrement",shopList)'>-</a>
            <input autocomplete="off" type="text" :value="shopList.skuNum" minnum="1" class="itxt" @change='changeSkuNum("text",shopList,$event)'>
            <a href="javascript:void(0)" class="plus" @click='changeSkuNum("increment",shopList)'>+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{shopList.skuNum*shopList.skuPrice}}</span>
          </li>
          <li class="cart-list-con7">
            <a href="javascript:;" class="sindelet" @click='delOne(shopList.skuId)'>删除</a>
            <br>
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="isCheckedAll">
        <span>全选</span>
      </div>
      <div class="option">
        <a href="javascript:;" @click='delSelect'>删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择
          <span>{{checkedNum}}</span>件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：{{allPrice}}.00</em>
          <i class="summoney"></i>
        </div>
        <div class="sumbtn">
          <a class="sum-btn" href="javascript:;" @click="$router.push('/trade')">结算</a>
        </div>
      </div>
    </div>
    <!-- 弹出框 -->
    <Dialog :isShowDia.sync='isShowDia'>
      <template v-slot:header>提示</template>
      <template>确定要删除<span style='color:red'>{{isDelOne? ' 该条 ' : ' 选中的 '}}</span>信息吗?点击确认删除！</template>
      <template #footer>
        <div class="btn-footer">
          <button class="btn btn-cancle" @click='isShowDia=false'>取消</button>
          <button class="btn btn-primary" @click='delOneShopCartInfo'>确定</button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script>
import { reqGetShopCartInfo, reqGetShopCartisCheckedInfo, reqPostShopCartisCheckedAllInfo, reqDelShopCartOneInfo, reqDelSelectShopCartInfo, reqPostAddOrUpdateCart } from '@/api';
import { skuNumReg } from '@/utils/rej';
import { debounce2 } from '@/utils/debounce';
export default {
  name: 'ShopCart',
  data() {
    return {
      // 购物车商品列表数据
      shopCartList: [],
      // 定义数据 储存所有要更新状态的商品 全选
      skuList: [],
      // 默认隐藏
      isShowDia: false,
      isDelOne: false,
      skuId: '',
      // 存储不需要删除的商品id
      leftCartInfoList: [],
      timerId: null,
      num: 0
    };
  },
  mounted() {
    // 发送请求 获取购物车商品数据
    this.getShopCartListData();
  },
  methods: {
    // 获取购物车商品列表数据的方法
    async getShopCartListData() {
      const result = await reqGetShopCartInfo();
      console.log('shopcart', result);
      if (result.code === 200) {
        this.shopCartList = result.data[0] ? result.data[0].cartInfoList : [];
      } else {
        console.log(result.message);
      }
    },
    // 单选请求
    async checkedCartInfo(shopList) {
      let isChecked = 1 - shopList.isChecked; // 相当于取反
      const result = await reqGetShopCartisCheckedInfo(shopList.skuId, isChecked);
      // 更新服务器数据后更新界面
      shopList.isChecked = isChecked;
    },
    delOne(skuId) {
      // 存储栓除删除一条的商品skuId
      this.skuId = skuId;
      this.isShowDia = true;
      this.isDelOne = true;
    },
    delSelect() {
      this.isShowDia = true;
      this.isDelOne = false;
      // 收集选中的待删除的商品skuid
      this.shopCartList.forEach(item => {
        if (item.isChecked === 1) {
          this.skuList.push(item.skuId);
        } else {
          // 存储不删除的商品用于更新界面用
          this.leftCartInfoList.push(item);
        }
      });
    },
    async delOneShopCartInfo() {
      // 1、判断删除的是单条数据按钮
      if (this.isDelOne) {
        // 2、发送请求删除一条数据
        const result = await reqDelShopCartOneInfo(this.skuId);
        if (result.code === 200) {
          // 3、关闭弹框
          this.isShowDia = false;
          // 4、重新发送购物车请求
          // 发送请求 获取购物车商品数据
          // this.getShopCartListData();
          // 4.1、优化
          this.shopCartList = this.shopCartList.filter(item => item.skuId !== this.skuId);
        } else {
          console.log(result.message);
        }
        // 删除一条return结束
        return;
      }

      // 1、删除多条购物车数据
      const result = await reqDelSelectShopCartInfo(this.skuList);
      if (result.code === 200) {
        // 2、关闭对话框
        this.isShowDia = false;
        // 3、更新数据更新界面
        this.getShopCartListData();
        // 3.2、优化
        // this.shopCartList = this.leftCartInfoList;
      } else {
        console.log(result.message);
      }
    },
    // 加 减 输入
    changeSkuNum(type, shopList, e) {
      // 如果有定时器，就清除
      if (this.timerId) clearTimeout(this.timerId);

      // 定义初始值用于存储差值
      // let num = 0;
      const oldNum = shopList.skuNum;
      switch (type) {
        case 'increment':
          // 小于200可以加
          if (shopList.skuNum < 200) {
            shopList.skuNum++;
            // num++;
            this.num++;
          }

          break;
        case 'decrement':
          if (shopList.skuNum > 1) {
            shopList.skuNum--;
            // num--;
            this.num--;
          }
          break;
        case 'text':
          // 输入的数值
          let newNum = e.target.value;
          // 如果输入的值符合正则设定的条件：为数字三位及以内
          if (skuNumReg.test(newNum)) {
            if (newNum > 200) {
              newNum = 200;
            }
            shopList.skuNum = newNum;
            // num = newNum - oldNum; // 差值
            this.num = newNum - oldNum;
          } else {
            e.target.value = oldNum; // 使用该方式来更新页面
            alert('输入内容有误！');
          }
          break;
      }
      // 判断没有更新则不需要发请求
      // if (num === 0) return;
      if (this.num === 0) return;
      this.timerId = setTimeout(async () => {
        // const result = await reqPostAddOrUpdateCart(shopList.skuId, num);
        const result = await reqPostAddOrUpdateCart(shopList.skuId, this.num);
        if (result.code === 200) {
          this.num = 0;
        } else {
          console.log(result.message);
        }
      }, 2000);
    }
    // 防抖
    // text:debounce(function () {console.log(111111)}, 1000)
  },
  computed: {
    isCheckedAll: {
      get() {
        // every 强调是一个整体 总所有的都满足条件 最终结果 才是true 有一个不满足就是false
        return this.shopCartList.every(shopList => shopList.isChecked === 1) && this.shopCartList.length;
      },
      async set(val) {
        this.skuList = [];
        this.shopCartList.forEach(shopList => {
          // // 全选是ture改为1 false改为0
          // let isChecked = val ? 1 : 0;
          // shopList.isChecked = isChecked;

          // 更新 数据
          shopList.isChecked = val ? 1 : 0;
          this.skuList.push(shopList.skuId);

          // 全选 使用单选接口 发送三次请求更改服务器选择状态
          // this.checkedCartInfo({ skuId: shopList.skuId, isChecked: 1 - isChecked });
        });
        // 全选请求 同意更新全选状态
        const result = await reqPostShopCartisCheckedAllInfo(this.skuList, val ? 1 : 0);
        alert('修改成功！');
      }
    },
    // 已选择商品数量
    checkedNum() {
      return this.shopCartList.reduce((pre, item) => pre + item.isChecked, 0);
    },
    // 总金额
    allPrice() {
      return this.shopCartList.reduce((pre, item) => {
        return pre + item.skuNum * item.skuPrice * item.isChecked;
      }, 0);
    }
  },
  beforeDestroy() {
    // 组件销毁之前清除定时器
    clearTimeout(this.timerId);
  }
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: 'Microsoft YaHei';
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
.btn-footer {
  position: absolute;
  right: 2px;
  bottom: 20px;
  .btn {
    width: 70px;
    height: 40px;
    border: none;
    border-radius: 4px;
    margin-right: 20px;
    cursor: pointer;
  }
  .btn-primary {
    color: #fff;
    background-color: #409eff;
    &:hover {
      background-color: #66b1ff;
    }
  }
  .btn-cancle {
    border: 1px solid #ccc;
    &:hover {
      background-color: #ecf5ff;
      color: #66b1ff;
    }
  }
}
</style>